/**
 * @author hewei
 * @version 1.0
 * @description: 1034. 边界着色
 * @date 2022/10/20 20:07
 */

public class ColorBorder {

    int[][] grid;
    int[][] step = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    int[][] ans;
    boolean[][] visited;
    int m;
    int n;
    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        this.grid = grid;
        m = grid.length;
        n = grid[0].length;
        visited = new boolean[m][n];
        ans = new int[m][n];
        for (int i = 0; i < m; i++) {
            if (n >= 0) System.arraycopy(grid[i], 0, ans[i], 0, n);
        }
        visited[row][col] = true;
        dfs(row, col, grid[row][col], color);
        return ans;
    }

    public void dfs(int i, int j, int target, int color) {
        int count = 0;
        for (int[] ints : step) {
            int x = i + ints[0];
            int y = j + ints[1];
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == target) {
                ++count;
                if (!visited[x][y]) {
                    visited[x][y] = true;
                    dfs(x, y, target, color);
                }
            }
        }
        if (count != 4) ans[i][j] = color;
    }
}
